﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SST.Phone.Model.VO;

namespace SST.Phone.Model.DAO
{
    /// <summary>
    /// Functions for the Settings table
    /// </summary>
    public class SettingsDAO : BaseDAO
    {
        public SettingsDAO(MainDataContext db) : base(db) { }

        /// <summary>
        /// Delete one
        /// </summary>
        /// <param name="name"></param>
        public void Delete(string name)
        {
            try
            {
                SettingItem item = _db.Settings.SingleOrDefault(s => s.Name == name);
                if (item != null)
                {
                    _db.Settings.DeleteOnSubmit(item);
                    _db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Error(ex);
            }
        }

        /// <summary>
        /// Delete then save
        /// </summary>
        /// <param name="vo"></param>
        public void Save(SettingItem vo)
        {
            try
            {
                Delete(vo.Name);

                SettingItem item = new SettingItem()
                {
                    Name = vo.Name,
                    Value = vo.Value
                };
                _db.Settings.InsertOnSubmit(item);
                _db.SubmitChanges();
            }
            catch (Exception ex)
            {
                Error(ex);
            }
        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="name"></param>
        /// <returns>Null if not found</returns>
        public SettingItem Load(string name)
        {
            try
            {
                return _db.Settings.SingleOrDefault(s => s.Name == name);
            }
            catch (Exception ex)
            {
                Error(ex);
            }
            return null;
        }

        public SettingItem Load(SettingItem.SETTING name)
        {
            return Load(name.ToString());
        }

        public string LoadValue(SettingItem.SETTING name)
        {
            SettingItem item = Load(name.ToString());
            if (item == null)
                return null;
            return item.Value;
        }
    }
}
